import React, { useState, useEffect } from 'react';
import { Form, message, Drawer } from 'antd';
import { Device, SlaveNode, ExtendedInfo, ProductTemplateFormValues } from '../../types/device';
import DeviceListTable from '../../components/device/DeviceListTable';
import DeviceForm from '../../components/device/DeviceForm';
import AddDeviceDrawer from '../../components/device/AddDeviceDrawer';
import DataManagementModal from '../../components/device/DataManagementModal';
import SlaveNodeManagement from '../../components/device/SlaveNodeManagement';
import ExtendedInfoPanel from '../../components/device/ExtendedInfoPanel';
import ProductTemplateModal from '../../components/device/ProductTemplateModal';

const DeviceLists: React.FC = () => {
  // 状态管理
  const [deviceData, setDeviceData] = useState<Device[]>([]);
  const [isDataModalVisible, setIsDataModalVisible] = useState(false);
  const [isAddNodeModalVisible, setIsAddNodeModalVisible] = useState(false);
  const [slaveNodes, setSlaveNodes] = useState<SlaveNode[]>([]);
  const [nodeForm] = Form.useForm();
  const [extendedInfo, setExtendedInfo] = useState<ExtendedInfo[]>([]);
  const [visible, setVisible] = useState(false);
  const [addExtInfoVisible, setAddExtInfoVisible] = useState(false);
  const [currentDevice, setCurrentDevice] = useState<Device | null>(null);
  const [form] = Form.useForm();
  const [extForm] = Form.useForm();
  const [isAdding, setIsAdding] = useState(false);
  const [addForm] = Form.useForm();
  const [isProductTemplateModalVisible, setIsProductTemplateModalVisible] = useState(false);

  // 初始化模拟数据
  useEffect(() => {
    // 模拟设备列表数据
    const mockData: Device[] = Array.from({ length: 5 }, (_, i) => ({
      key: `device-${i}`,
      index: i + 1,
      name: `设备${i + 1}`,
      sn: `SN${10000 + i}`,
      protocol: ['MQTT', 'HTTP', 'CoAP'][i % 3],
      dataCycle: `${i + 1}分钟`,
      project: ['智慧工厂', '智能建筑', '智慧城市'][i % 3],
      dataManagement: '已启用',
    }));
    setDeviceData(mockData);

    // 模拟扩展信息数据
    const mockExtInfo: ExtendedInfo[] = Array.from({ length: 3 }, (_, i) => ({
      key: `ext-${i}`,
      index: i + 1,
      name: `扩展字段${i + 1}`,
      type: ['数值', '字符串', '布尔值'][i % 3],
      enabled: i % 2 === 0,
    }));
    setExtendedInfo(mockExtInfo);
  }, []);

  // 处理添加设备
  const handleAddDevice = () => {
    setIsAdding(true);
    addForm.resetFields();
  };

  // 提交添加设备表单
  const handleAddSubmit = async (values: any) => {
    try {
      const newDevice: Device = {
        key: `device-${Date.now()}`,
        index: deviceData.length + 1,
        name: values.deviceName,
        sn: values.deviceSN || `SN${10000 + deviceData.length}`,
        protocol: values.protocol,
        dataCycle: '1分钟',
        project: values.project,
        dataManagement: '已启用',
      };
      setDeviceData([...deviceData, newDevice]);
      message.success('设备添加成功');
      setIsAdding(false);
    } catch (error) {
      message.error('表单验证失败，请检查必填项');
    }
  };

  // 处理关闭添加设备抽屉
  const handleCloseAddDevice = () => {
    setIsAdding(false);
  };

  // 编辑按钮点击事件
  const handleEdit = (record: Device) => {
    setCurrentDevice(record);
    // 填充表单数据
    form.setFieldsValue({
      project: record.project,
      deviceName: record.name,
      deviceSN: record.sn,
      protocol: record.protocol,
    });
    setVisible(true);
  };

  // 保存基本信息
  const handleSaveBasicInfo = () => {
    form.validateFields()
      .then(values => {
        message.success('基本信息保存成功');
        // 更新设备数据
        if (currentDevice) {
          setDeviceData(deviceData.map(device => 
            device.key === currentDevice.key 
              ? { ...device, name: values.deviceName, protocol: values.protocol, project: values.project }
              : device
          ));
        }
        setVisible(false);
      })
      .catch(info => {
        message.error('表单验证失败，请检查输入');
      });
  };

  // 编辑扩展信息
  const handleEditExtInfo = (record: ExtendedInfo) => {
    message.info(`编辑扩展信息: ${record.name}`);
    // 这里可以添加编辑扩展信息的具体逻辑
  };

  // 删除扩展信息
  const handleDeleteExtInfo = (key: string) => {
    setExtendedInfo(extendedInfo.filter(item => item.key !== key));
    message.success('扩展信息已删除');
  };

  // 切换扩展信息启用状态
  const handleToggleExtInfo = (key: string, checked: boolean) => {
    setExtendedInfo(
      extendedInfo.map(item =>
        item.key === key ? { ...item, enabled: checked } : item
      )
    );
  };

  // 添加扩展信息
  const handleAddExtInfo = (info: ExtendedInfo) => {
    setExtendedInfo([...extendedInfo, info]);
  };

  // 打开数据管理模态框
  const handleOpenDataModal = (record: Device) => {
    setCurrentDevice(record);
    setIsDataModalVisible(true);
  };

  // 关闭数据管理模态框
  const handleCloseDataModal = () => {
    setIsDataModalVisible(false);
  };

  // 打开产品模板模态框
  const handleOpenProductTemplateModal = () => {
    setIsProductTemplateModalVisible(true);
  };

  // 关闭产品模板模态框
  const handleCloseProductTemplateModal = () => {
    setIsProductTemplateModalVisible(false);
  };

  // 保存产品模板设置
  const handleSaveProductTemplate = (values: ProductTemplateFormValues) => {
    message.success('产品模板设置已保存');
    setIsProductTemplateModalVisible(false);
    // 这里可以根据需要处理保存后的逻辑
  };

  // 保存数据管理设置
  const handleSaveDataManagement = (values: any) => {
    message.success('数据管理设置已保存');
    setIsDataModalVisible(false);
  };

  // 删除设备
  const handleDeleteDevice = (device: Device) => {
    setDeviceData(deviceData.filter(d => d.key !== device.key));
  };

  // 添加从设备节点
  const handleAddNode = (node: SlaveNode) => {
    setSlaveNodes([...slaveNodes, node]);
  };

  // 删除从设备节点
  const handleDeleteNode = (key: string) => {
    setSlaveNodes(slaveNodes.filter(node => node.key !== key));
  };

  return (
    <div className="device-list-container" style={{ width: '100%', height: '100%', margin: 0, padding: '20px', boxSizing: 'border-box' }}>
      {/* 设备列表表格 */}
      <DeviceListTable
        devices={deviceData}
        onAddDevice={handleAddDevice}
        onEditDevice={handleEdit}
        onDeleteDevice={handleDeleteDevice}
        onOpenDataModal={handleOpenDataModal}
        onOpenProductTemplateModal={handleOpenProductTemplateModal}
      />

      {/* 编辑抽屉 */}
      <Drawer
        title="编辑设备"
        placement="right"
        onClose={() => setVisible(false)}
        open={visible}
        width={600}
      >
        <DeviceForm
          form={form}
          extForm={extForm}
          isEdit={true}
          currentDevice={currentDevice}
          onSaveBasicInfo={handleSaveBasicInfo}
          onToggleExtInfo={handleToggleExtInfo}
          onDeleteExtInfo={handleDeleteExtInfo}
          onEditExtInfo={handleEditExtInfo}
          extendedInfo={extendedInfo}
          setAddExtInfoVisible={setAddExtInfoVisible}
        />
        
        {/* 扩展信息面板 - 处理添加、编辑、删除扩展信息 */}
        <ExtendedInfoPanel
          extendedInfo={extendedInfo}
          onToggleExtInfo={handleToggleExtInfo}
          onDeleteExtInfo={handleDeleteExtInfo}
          onEditExtInfo={handleEditExtInfo}
          addExtInfoVisible={addExtInfoVisible}
          setAddExtInfoVisible={setAddExtInfoVisible}
          extForm={extForm}
          onAddExtInfo={handleAddExtInfo}
        />
      </Drawer>

      {/* 添加设备抽屉 */}
      <AddDeviceDrawer
        visible={isAdding}
        onClose={handleCloseAddDevice}
        onSubmit={handleAddSubmit}
        addForm={addForm}
      />

      {/* 数据管理模态框 */}
      <DataManagementModal
        visible={isDataModalVisible}
        onCancel={handleCloseDataModal}
        onSave={handleSaveDataManagement}
      />

      {/* 产品模板模态框 */}
      <ProductTemplateModal
        visible={isProductTemplateModalVisible}
        onCancel={handleCloseProductTemplateModal}
        onSave={handleSaveProductTemplate}
      />

      {/* 扩展信息面板 */}
      {/* 注意：这个面板在编辑抽屉中已经包含，这里仅作为示例 */}
      
      {/* 从设备节点管理 */}
      {/* 注意：这个组件可以根据需要在适当的地方使用 */}
    </div>
  );
};

export default DeviceLists;